using Microsoft.Phone.Controls.Primitives;
using Microsoft.Phone.Shell;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Microsoft.Phone.Controls
{
	[TemplateVisualState(GroupName = "VisibilityStates", Name = "Open"), TemplateVisualState(GroupName = "VisibilityStates", Name = "OpenReversed"), TemplateVisualState(GroupName = "VisibilityStates", Name = "OpenLandscapeReversed"), TemplateVisualState(GroupName = "VisibilityStates", Name = "OpenLandscape"), TemplateVisualState(GroupName = "VisibilityStates", Name = "Closed")]
	public class ContextMenu : MenuBase
	{
		private const double LandscapeWidth = 480.0;
		private const double SystemTrayLandscapeWidth = 72.0;
		private const double ApplicationBarLandscapeWidth = 72.0;
		private const double TotalBorderWidth = 8.0;
		private const string VisibilityGroupName = "VisibilityStates";
		private const string OpenVisibilityStateName = "Open";
		private const string OpenReversedVisibilityStateName = "OpenReversed";
		private const string ClosedVisibilityStateName = "Closed";
		private const string OpenLandscapeVisibilityStateName = "OpenLandscape";
		private const string OpenLandscapeReversedVisibilityStateName = "OpenLandscapeReversed";
		private StackPanel _outerPanel;
		private Grid _innerGrid;
		private PhoneApplicationPage _page;
		private readonly List<ApplicationBarIconButton> _applicationBarIconButtons = new List<ApplicationBarIconButton>();
		private Storyboard _backgroundResizeStoryboard;
		private List<Storyboard> _openingStoryboard;
		private bool _openingStoryboardPlaying;
		private DateTime _openingStoryboardReleaseThreshold;
		private PhoneApplicationFrame _rootVisual;
		private Point _mousePosition;
		private DependencyObject _owner;
		private Popup _popup;
		private Panel _overlay;
		private Point _popupAlignmentPoint;
		private bool _settingIsOpen;
		private bool _reversed;
		public static readonly DependencyProperty IsZoomEnabledProperty = DependencyProperty.Register("IsZoomEnabled", typeof(bool), typeof(ContextMenu), new PropertyMetadata(true));
		public static readonly DependencyProperty IsFadeEnabledProperty = DependencyProperty.Register("IsFadeEnabled", typeof(bool), typeof(ContextMenu), new PropertyMetadata(true));
		public static readonly DependencyProperty VerticalOffsetProperty = DependencyProperty.Register("VerticalOffset", typeof(double), typeof(ContextMenu), new PropertyMetadata(0.0, new PropertyChangedCallback(ContextMenu.OnVerticalOffsetChanged)));
		public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register("IsOpen", typeof(bool), typeof(ContextMenu), new PropertyMetadata(false, new PropertyChangedCallback(ContextMenu.OnIsOpenChanged)));
		public static readonly DependencyProperty RegionOfInterestProperty = DependencyProperty.Register("RegionOfInterest", typeof(Rect?), typeof(ContextMenu), null);
		private static readonly DependencyProperty ApplicationBarMirrorProperty = DependencyProperty.Register("ApplicationBarMirror", typeof(IApplicationBar), typeof(ContextMenu), new PropertyMetadata(new PropertyChangedCallback(ContextMenu.OnApplicationBarMirrorChanged)));
		public event RoutedEventHandler Opened;
		public event RoutedEventHandler Closed;
		public DependencyObject Owner
		{
			get
			{
				return this._owner;
			}
			internal set
			{
				if (this._owner != null)
				{
					FrameworkElement frameworkElement = this._owner as FrameworkElement;
					if (frameworkElement != null)
					{
						frameworkElement.remove_Hold(new EventHandler<GestureEventArgs>(this.OnOwnerHold));
						frameworkElement.remove_Loaded(new RoutedEventHandler(this.OnOwnerLoaded));
						frameworkElement.remove_Unloaded(new RoutedEventHandler(this.OnOwnerUnloaded));
						this.OnOwnerUnloaded(null, null);
					}
				}
				this._owner = value;
				if (this._owner != null)
				{
					FrameworkElement frameworkElement2 = this._owner as FrameworkElement;
					if (frameworkElement2 != null)
					{
						frameworkElement2.add_Hold(new EventHandler<GestureEventArgs>(this.OnOwnerHold));
						frameworkElement2.add_Loaded(new RoutedEventHandler(this.OnOwnerLoaded));
						frameworkElement2.add_Unloaded(new RoutedEventHandler(this.OnOwnerUnloaded));
						DependencyObject dependencyObject = frameworkElement2;
						while (dependencyObject != null)
						{
							dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
							if (dependencyObject != null && dependencyObject == this._rootVisual)
							{
								this.OnOwnerLoaded(null, null);
								return;
							}
						}
					}
				}
			}
		}
		public bool IsZoomEnabled
		{
			get
			{
				return (bool)base.GetValue(ContextMenu.IsZoomEnabledProperty);
			}
			set
			{
				base.SetValue(ContextMenu.IsZoomEnabledProperty, value);
			}
		}
		public bool IsFadeEnabled
		{
			get
			{
				return (bool)base.GetValue(ContextMenu.IsFadeEnabledProperty);
			}
			set
			{
				base.SetValue(ContextMenu.IsFadeEnabledProperty, value);
			}
		}
		[TypeConverter(typeof(LengthConverter))]
		public double VerticalOffset
		{
			get
			{
				return (double)base.GetValue(ContextMenu.VerticalOffsetProperty);
			}
			set
			{
				base.SetValue(ContextMenu.VerticalOffsetProperty, value);
			}
		}
		public bool IsOpen
		{
			get
			{
				return (bool)base.GetValue(ContextMenu.IsOpenProperty);
			}
			set
			{
				base.SetValue(ContextMenu.IsOpenProperty, value);
			}
		}
		public Rect? RegionOfInterest
		{
			get
			{
				return (Rect?)base.GetValue(ContextMenu.RegionOfInterestProperty);
			}
			set
			{
				base.SetValue(ContextMenu.RegionOfInterestProperty, value);
			}
		}
		private static void OnVerticalOffsetChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
		{
			((ContextMenu)o).UpdateContextMenuPlacement();
		}
		private static void OnIsOpenChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
		{
			((ContextMenu)o).OnIsOpenChanged((bool)e.get_NewValue());
		}
		private void OnIsOpenChanged(bool newValue)
		{
			if (!this._settingIsOpen)
			{
				if (newValue)
				{
					this.OpenPopup(this._mousePosition);
					return;
				}
				this.ClosePopup();
			}
		}
		protected virtual void OnOpened(RoutedEventArgs e)
		{
			this.UpdateContextMenuPlacement();
			this.SetRenderTransform();
			this.UpdateVisualStates(true);
			RoutedEventHandler opened = this.Opened;
			if (opened != null)
			{
				opened.Invoke(this, e);
			}
		}
		private void SetRenderTransform()
		{
			if (!DesignerProperties.get_IsInDesignTool() && !this._rootVisual.get_Orientation().IsPortrait())
			{
				if (this._outerPanel != null)
				{
					this._outerPanel.set_RenderTransformOrigin(new Point(0.0, 0.5));
				}
				if (this._innerGrid != null)
				{
					double num = (double)(this._reversed ? 1 : 0);
					this._innerGrid.set_RenderTransformOrigin(new Point(num, 0.0));
				}
			}
			else
			{
				double num2 = this._popupAlignmentPoint.get_X() / base.get_Width();
				if (this._outerPanel != null)
				{
					this._outerPanel.set_RenderTransformOrigin(new Point(num2, 0.0));
				}
				if (this._innerGrid != null)
				{
					double num3 = (double)(this._reversed ? 1 : 0);
					this._innerGrid.set_RenderTransformOrigin(new Point(0.0, num3));
					return;
				}
			}
		}
		protected virtual void OnClosed(RoutedEventArgs e)
		{
			this.UpdateVisualStates(true);
			RoutedEventHandler closed = this.Closed;
			if (closed != null)
			{
				closed.Invoke(this, e);
			}
		}
		public ContextMenu()
		{
			base.set_DefaultStyleKey(typeof(ContextMenu));
			this._openingStoryboard = new List<Storyboard>();
			base.add_LayoutUpdated(new EventHandler(this.OnLayoutUpdated));
		}
		public override void OnApplyTemplate()
		{
			if (this._openingStoryboard != null)
			{
				using (List<Storyboard>.Enumerator enumerator = this._openingStoryboard.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						Storyboard current = enumerator.get_Current();
						current.remove_Completed(new EventHandler(this.OnStoryboardCompleted));
					}
				}
				this._openingStoryboard.Clear();
			}
			this._openingStoryboardPlaying = false;
			base.OnApplyTemplate();
			this.SetDefaultStyle();
			FrameworkElement frameworkElement = VisualTreeHelper.GetChild(this, 0) as FrameworkElement;
			if (frameworkElement != null)
			{
				IEnumerator enumerator2 = VisualStateManager.GetVisualStateGroups(frameworkElement).GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						VisualStateGroup visualStateGroup = (VisualStateGroup)enumerator2.get_Current();
						if ("VisibilityStates" == visualStateGroup.get_Name())
						{
							IEnumerator enumerator3 = visualStateGroup.get_States().GetEnumerator();
							try
							{
								while (enumerator3.MoveNext())
								{
									VisualState visualState = (VisualState)enumerator3.get_Current();
									if (("Open" == visualState.get_Name() || "OpenLandscape" == visualState.get_Name() || "OpenReversed" == visualState.get_Name() || "OpenLandscapeReversed" == visualState.get_Name()) && visualState.get_Storyboard() != null)
									{
										this._openingStoryboard.Add(visualState.get_Storyboard());
										visualState.get_Storyboard().add_Completed(new EventHandler(this.OnStoryboardCompleted));
									}
								}
							}
							finally
							{
								IDisposable disposable = enumerator3 as IDisposable;
								if (disposable != null)
								{
									disposable.Dispose();
								}
							}
						}
					}
				}
				finally
				{
					IDisposable disposable2 = enumerator2 as IDisposable;
					if (disposable2 != null)
					{
						disposable2.Dispose();
					}
				}
			}
			this._outerPanel = (base.GetTemplateChild("OuterPanel") as StackPanel);
			this._innerGrid = (base.GetTemplateChild("InnerGrid") as Grid);
			bool flag = DesignerProperties.get_IsInDesignTool() || this._rootVisual.get_Orientation().IsPortrait();
			this.SetRenderTransform();
			if (this.IsOpen)
			{
				if (this._innerGrid != null)
				{
					this._innerGrid.set_MinHeight(flag ? 0.0 : this._rootVisual.get_ActualWidth());
				}
				this.UpdateVisualStates(true);
			}
		}
		private void SetDefaultStyle()
		{
			SolidColorBrush solidColorBrush;
			SolidColorBrush solidColorBrush2;
			if (!DesignerProperties.get_IsInDesignTool() && !base.get_Resources().IsDarkThemeActive())
			{
				solidColorBrush = new SolidColorBrush(Colors.get_Black());
				solidColorBrush2 = new SolidColorBrush(Colors.get_White());
			}
			else
			{
				solidColorBrush = new SolidColorBrush(Colors.get_White());
				solidColorBrush2 = new SolidColorBrush(Colors.get_Black());
			}
			Style style = new Style(typeof(ContextMenu));
			Setter setter = new Setter(Control.BackgroundProperty, solidColorBrush);
			Setter setter2 = new Setter(Control.BorderBrushProperty, solidColorBrush2);
			if (base.get_Style() == null)
			{
				style.get_Setters().Add(setter);
				style.get_Setters().Add(setter2);
			}
			else
			{
				bool flag = false;
				bool flag2 = false;
				using (IEnumerator<SetterBase> enumerator = base.get_Style().get_Setters().GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						Setter setter3 = (Setter)enumerator.get_Current();
						if (setter3.get_Property() == Control.BackgroundProperty)
						{
							flag = true;
						}
						else
						{
							if (setter3.get_Property() == Control.BorderBrushProperty)
							{
								flag2 = true;
							}
						}
						style.get_Setters().Add(new Setter(setter3.get_Property(), setter3.get_Value()));
					}
				}
				if (!flag)
				{
					style.get_Setters().Add(setter);
				}
				if (!flag2)
				{
					style.get_Setters().Add(setter2);
				}
			}
			base.set_Style(style);
		}
		private void OnStoryboardCompleted(object sender, EventArgs e)
		{
			this._openingStoryboardPlaying = false;
		}
		private void UpdateVisualStates(bool useTransitions)
		{
			string text;
			if (this.IsOpen)
			{
				if (this._openingStoryboard != null)
				{
					this._openingStoryboardPlaying = true;
					this._openingStoryboardReleaseThreshold = DateTime.get_UtcNow().AddSeconds(0.3);
				}
				if (this._rootVisual != null && this._rootVisual.get_Orientation().IsPortrait())
				{
					if (this._outerPanel != null)
					{
						this._outerPanel.set_Orientation(0);
					}
					text = (this._reversed ? "OpenReversed" : "Open");
				}
				else
				{
					if (this._outerPanel != null)
					{
						this._outerPanel.set_Orientation(1);
					}
					text = (this._reversed ? "OpenLandscapeReversed" : "OpenLandscape");
				}
				if (this._backgroundResizeStoryboard != null)
				{
					this._backgroundResizeStoryboard.Begin();
				}
			}
			else
			{
				text = "Closed";
			}
			VisualStateManager.GoToState(this, text, useTransitions);
		}
		private bool PositionIsOnScreenRight(double position)
		{
			if (18 != this._rootVisual.get_Orientation())
			{
				return position < this._rootVisual.get_ActualHeight() / 2.0;
			}
			return position > this._rootVisual.get_ActualHeight() / 2.0;
		}
		protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
		{
			if (e == null)
			{
				throw new ArgumentNullException("e");
			}
			e.set_Handled(true);
			base.OnMouseLeftButtonDown(e);
		}
		protected override void OnKeyDown(KeyEventArgs e)
		{
			if (e == null)
			{
				throw new ArgumentNullException("e");
			}
			Key key = e.get_Key();
			if (key != 8)
			{
				switch (key)
				{
				case 15:
					this.FocusNextItem(false);
					e.set_Handled(true);
					break;
				case 17:
					this.FocusNextItem(true);
					e.set_Handled(true);
					break;
				}
			}
			else
			{
				this.ClosePopup();
				e.set_Handled(true);
			}
			base.OnKeyDown(e);
		}
		private void OnLayoutUpdated(object sender, EventArgs e)
		{
			if (Application.get_Current().get_RootVisual() != null)
			{
				this.InitializeRootVisual();
				base.remove_LayoutUpdated(new EventHandler(this.OnLayoutUpdated));
			}
		}
		private void OnRootVisualMouseMove(object sender, MouseEventArgs e)
		{
			this._mousePosition = e.GetPosition(null);
		}
		private void OnRootVisualManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
		{
			if (this._openingStoryboardPlaying && DateTime.get_UtcNow() <= this._openingStoryboardReleaseThreshold)
			{
				this.IsOpen = false;
			}
		}
		private void OnOwnerHold(object sender, GestureEventArgs e)
		{
			if (!this.IsOpen)
			{
				this.OpenPopup(e.GetPosition(null));
				e.set_Handled(true);
			}
		}
		private static void OnApplicationBarMirrorChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
		{
			((ContextMenu)o).OnApplicationBarMirrorChanged((IApplicationBar)e.get_OldValue(), (IApplicationBar)e.get_NewValue());
		}
		private void OnApplicationBarMirrorChanged(IApplicationBar oldValue, IApplicationBar newValue)
		{
			if (oldValue != null)
			{
				oldValue.remove_StateChanged(new EventHandler<ApplicationBarStateChangedEventArgs>(this.OnEventThatClosesContextMenu));
			}
			if (newValue != null)
			{
				newValue.add_StateChanged(new EventHandler<ApplicationBarStateChangedEventArgs>(this.OnEventThatClosesContextMenu));
			}
		}
		private void OnEventThatClosesContextMenu(object sender, EventArgs e)
		{
			this.IsOpen = false;
		}
		private void OnOwnerLoaded(object sender, RoutedEventArgs e)
		{
			if (this._page == null)
			{
				this.InitializeRootVisual();
				if (this._rootVisual != null)
				{
					this._page = (this._rootVisual.get_Content() as PhoneApplicationPage);
					if (this._page != null)
					{
						this._page.add_BackKeyPress(new EventHandler<CancelEventArgs>(this.OnPageBackKeyPress));
						DependencyProperty arg_7A_1 = ContextMenu.ApplicationBarMirrorProperty;
						Binding binding = new Binding();
						binding.set_Source(this._page);
						binding.set_Path(new PropertyPath("ApplicationBar", new object[0]));
						base.SetBinding(arg_7A_1, binding);
					}
				}
			}
		}
		private void OnOwnerUnloaded(object sender, RoutedEventArgs e)
		{
			if (this._rootVisual != null)
			{
				this._rootVisual.remove_MouseMove(new MouseEventHandler(this.OnRootVisualMouseMove));
				this._rootVisual.remove_ManipulationCompleted(new EventHandler<ManipulationCompletedEventArgs>(this.OnRootVisualManipulationCompleted));
				this._rootVisual.remove_OrientationChanged(new EventHandler<OrientationChangedEventArgs>(this.OnEventThatClosesContextMenu));
			}
			if (this._page != null)
			{
				this._page.remove_BackKeyPress(new EventHandler<CancelEventArgs>(this.OnPageBackKeyPress));
				base.ClearValue(ContextMenu.ApplicationBarMirrorProperty);
				this._page = null;
			}
		}
		private void OnPageBackKeyPress(object sender, CancelEventArgs e)
		{
			if (this.IsOpen)
			{
				this.IsOpen = false;
				e.set_Cancel(true);
			}
		}
		private static GeneralTransform SafeTransformToVisual(UIElement element, UIElement visual)
		{
			GeneralTransform result;
			try
			{
				result = element.TransformToVisual(visual);
			}
			catch (ArgumentException)
			{
				result = new TranslateTransform();
			}
			return result;
		}
		private void InitializeRootVisual()
		{
			if (this._rootVisual == null)
			{
				this._rootVisual = (Application.get_Current().get_RootVisual() as PhoneApplicationFrame);
				if (this._rootVisual != null)
				{
					this._rootVisual.remove_MouseMove(new MouseEventHandler(this.OnRootVisualMouseMove));
					this._rootVisual.add_MouseMove(new MouseEventHandler(this.OnRootVisualMouseMove));
					this._rootVisual.remove_ManipulationCompleted(new EventHandler<ManipulationCompletedEventArgs>(this.OnRootVisualManipulationCompleted));
					this._rootVisual.add_ManipulationCompleted(new EventHandler<ManipulationCompletedEventArgs>(this.OnRootVisualManipulationCompleted));
					this._rootVisual.remove_OrientationChanged(new EventHandler<OrientationChangedEventArgs>(this.OnEventThatClosesContextMenu));
					this._rootVisual.add_OrientationChanged(new EventHandler<OrientationChangedEventArgs>(this.OnEventThatClosesContextMenu));
				}
			}
		}
		private void FocusNextItem(bool down)
		{
			int count = base.get_Items().get_Count();
			int num = down ? -1 : count;
			MenuItem menuItem = FocusManager.GetFocusedElement() as MenuItem;
			if (menuItem != null && this == menuItem.ParentMenuBase)
			{
				num = base.get_ItemContainerGenerator().IndexFromContainer(menuItem);
			}
			int num2 = num;
			do
			{
				num2 = (num2 + count + ((!down) ? -1 : 1)) % count;
				MenuItem menuItem2 = base.get_ItemContainerGenerator().ContainerFromIndex(num2) as MenuItem;
				if (menuItem2 != null && menuItem2.get_IsEnabled() && menuItem2.Focus())
				{
					return;
				}
			}
			while (num2 != num);
		}
		internal void ChildMenuItemClicked()
		{
			this.ClosePopup();
		}
		private void OnContextMenuOrRootVisualSizeChanged(object sender, SizeChangedEventArgs e)
		{
			this.UpdateContextMenuPlacement();
		}
		private void OnOverlayMouseButtonUp(object sender, MouseButtonEventArgs e)
		{
			List<UIElement> list = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), this._rootVisual) as List<UIElement>;
			if (!list.Contains(this))
			{
				this.ClosePopup();
			}
			e.set_Handled(true);
		}
		private void UpdateContextMenuPlacement()
		{
			if (this._rootVisual != null && this._overlay != null)
			{
				Point popupAlignmentPoint = new Point(this._popupAlignmentPoint.get_X(), this._popupAlignmentPoint.get_Y());
				bool flag;
				double num = (flag = this._rootVisual.get_Orientation().IsPortrait()) ? this._rootVisual.get_ActualWidth() : this._rootVisual.get_ActualHeight();
				double num2 = flag ? this._rootVisual.get_ActualHeight() : this._rootVisual.get_ActualWidth();
				Rect rect = new Rect(0.0, 0.0, num, num2);
				if (this._page != null)
				{
					rect = ContextMenu.SafeTransformToVisual(this._page, this._rootVisual).TransformBounds(new Rect(0.0, 0.0, this._page.get_ActualWidth(), this._page.get_ActualHeight()));
				}
				if (flag && this._rootVisual != null)
				{
					double y;
					double num3;
					if (this.RegionOfInterest.get_HasValue())
					{
						y = this.RegionOfInterest.get_Value().get_Y();
						num3 = this.RegionOfInterest.get_Value().get_Height();
					}
					else
					{
						if (this.Owner is FrameworkElement)
						{
							FrameworkElement frameworkElement = (FrameworkElement)this.Owner;
							GeneralTransform generalTransform = frameworkElement.TransformToVisual(this._rootVisual);
							y = generalTransform.Transform(new Point(0.0, 0.0)).get_Y();
							num3 = frameworkElement.get_ActualHeight();
						}
						else
						{
							y = this._popupAlignmentPoint.get_Y();
							num3 = 0.0;
						}
					}
					popupAlignmentPoint.set_Y(y + num3);
					this._reversed = false;
					if (popupAlignmentPoint.get_Y() > rect.get_Bottom() - base.get_ActualHeight())
					{
						popupAlignmentPoint.set_Y(y - base.get_ActualHeight());
						this._reversed = true;
						if (popupAlignmentPoint.get_Y() < rect.get_Top())
						{
							popupAlignmentPoint = this._popupAlignmentPoint;
							this._reversed = false;
							if (popupAlignmentPoint.get_Y() > rect.get_Bottom() - base.get_ActualHeight())
							{
								this._reversed = true;
								if (popupAlignmentPoint.get_Y() < rect.get_Top())
								{
									popupAlignmentPoint.set_Y(rect.get_Bottom() - base.get_ActualHeight());
									this._reversed = true;
								}
							}
						}
					}
				}
				double num4 = popupAlignmentPoint.get_X();
				double num5 = popupAlignmentPoint.get_Y();
				num5 += this.VerticalOffset;
				if (flag)
				{
					num4 = rect.get_Left();
					base.set_Width(rect.get_Width());
					if (this._innerGrid != null)
					{
						this._innerGrid.set_Width(base.get_Width());
					}
				}
				else
				{
					if (this.PositionIsOnScreenRight(num5))
					{
						base.set_Width(SystemTray.get_IsVisible() ? 408.0 : 480.0);
						num4 = (SystemTray.get_IsVisible() ? 72.0 : 0.0);
						this._reversed = true;
					}
					else
					{
						base.set_Width((this._page.get_ApplicationBar() == null || !this._page.get_ApplicationBar().get_IsVisible()) ? 480.0 : 408.0);
						num4 = rect.get_Width() - base.get_Width() + (SystemTray.get_IsVisible() ? 72.0 : 0.0);
						this._reversed = false;
					}
					if (this._innerGrid != null)
					{
						this._innerGrid.set_Width(base.get_Width() - 8.0);
					}
					num5 = 0.0;
				}
				num4 = Math.Max(num4, 0.0);
				Canvas.SetLeft(this, num4);
				Canvas.SetTop(this, num5);
				this._overlay.set_Width(num);
				this._overlay.set_Height(num2);
			}
		}
		private void OpenPopup(Point position)
		{
			this._popupAlignmentPoint = position;
			this.InitializeRootVisual();
			bool flag;
			if (flag = this._rootVisual.get_Orientation().IsPortrait())
			{
				if (this._innerGrid != null)
				{
					this._innerGrid.set_MinHeight(0.0);
				}
			}
			else
			{
				if (this._innerGrid != null)
				{
					this._innerGrid.set_MinHeight(this._rootVisual.get_ActualWidth());
				}
			}
			Canvas canvas = new Canvas();
			canvas.set_Background(new SolidColorBrush(Colors.get_Transparent()));
			this._overlay = canvas;
			this._overlay.add_MouseLeftButtonUp(new MouseButtonEventHandler(this.OnOverlayMouseButtonUp));
			if (this.IsZoomEnabled && this._rootVisual != null)
			{
				double num = flag ? this._rootVisual.get_ActualWidth() : this._rootVisual.get_ActualHeight();
				double num2 = flag ? this._rootVisual.get_ActualHeight() : this._rootVisual.get_ActualWidth();
				Rectangle rectangle = new Rectangle();
				rectangle.set_Width(num);
				rectangle.set_Height(num2);
				rectangle.set_Fill((Brush)Application.get_Current().get_Resources().get_Item("PhoneBackgroundBrush"));
				rectangle.set_CacheMode(new BitmapCache());
				UIElement uIElement = rectangle;
				this._overlay.get_Children().Insert(0, uIElement);
				FrameworkElement frameworkElement = this._owner as FrameworkElement;
				if (frameworkElement != null)
				{
					frameworkElement.set_Opacity(0.0);
				}
				WriteableBitmap writeableBitmap = new WriteableBitmap((int)num, (int)num2);
				writeableBitmap.Render(this._rootVisual, null);
				writeableBitmap.Invalidate();
				ScaleTransform scaleTransform = new ScaleTransform();
				scaleTransform.set_CenterX(num / 2.0);
				scaleTransform.set_CenterY(num2 / 2.0);
				Transform transform = scaleTransform;
				Image image = new Image();
				image.set_Source(writeableBitmap);
				image.set_RenderTransform(transform);
				image.set_CacheMode(new BitmapCache());
				UIElement uIElement2 = image;
				this._overlay.get_Children().Insert(1, uIElement2);
				Rectangle rectangle2 = new Rectangle();
				rectangle2.set_Width(num);
				rectangle2.set_Height(num2);
				rectangle2.set_Fill((Brush)Application.get_Current().get_Resources().get_Item("PhoneBackgroundBrush"));
				rectangle2.set_Opacity(0.0);
				rectangle2.set_CacheMode(new BitmapCache());
				UIElement uIElement3 = rectangle2;
				this._overlay.get_Children().Insert(2, uIElement3);
				if (frameworkElement != null)
				{
					((FrameworkElement)this.Owner).set_Opacity(1.0);
					Point point = ContextMenu.SafeTransformToVisual(frameworkElement, this._rootVisual).Transform(default(Point));
					Rectangle rectangle3 = new Rectangle();
					rectangle3.set_Width(frameworkElement.get_ActualWidth());
					rectangle3.set_Height(frameworkElement.get_ActualHeight());
					rectangle3.set_Fill(new SolidColorBrush(Colors.get_Transparent()));
					rectangle3.set_CacheMode(new BitmapCache());
					UIElement uIElement4 = rectangle3;
					Canvas.SetLeft(uIElement4, point.get_X());
					Canvas.SetTop(uIElement4, point.get_Y());
					this._overlay.get_Children().Insert(3, uIElement4);
					Image image2 = new Image();
					image2.set_Source(new WriteableBitmap(frameworkElement, null));
					UIElement uIElement5 = image2;
					Canvas.SetLeft(uIElement5, point.get_X());
					Canvas.SetTop(uIElement5, point.get_Y());
					this._overlay.get_Children().Insert(4, uIElement5);
				}
				double num3 = 1.0;
				double num4 = 0.94;
				TimeSpan timeSpan = TimeSpan.FromSeconds(0.42);
				ExponentialEase exponentialEase = new ExponentialEase();
				exponentialEase.set_EasingMode(2);
				IEasingFunction easingFunction = exponentialEase;
				this._backgroundResizeStoryboard = new Storyboard();
				DoubleAnimation doubleAnimation = new DoubleAnimation();
				doubleAnimation.set_From(new double?(num3));
				doubleAnimation.set_To(new double?(num4));
				doubleAnimation.set_Duration(timeSpan);
				doubleAnimation.set_EasingFunction(easingFunction);
				DoubleAnimation doubleAnimation2 = doubleAnimation;
				Storyboard.SetTarget(doubleAnimation2, transform);
				Storyboard.SetTargetProperty(doubleAnimation2, new PropertyPath(ScaleTransform.ScaleXProperty));
				this._backgroundResizeStoryboard.get_Children().Add(doubleAnimation2);
				DoubleAnimation doubleAnimation3 = new DoubleAnimation();
				doubleAnimation3.set_From(new double?(num3));
				doubleAnimation3.set_To(new double?(num4));
				doubleAnimation3.set_Duration(timeSpan);
				doubleAnimation3.set_EasingFunction(easingFunction);
				DoubleAnimation doubleAnimation4 = doubleAnimation3;
				Storyboard.SetTarget(doubleAnimation4, transform);
				Storyboard.SetTargetProperty(doubleAnimation4, new PropertyPath(ScaleTransform.ScaleYProperty));
				this._backgroundResizeStoryboard.get_Children().Add(doubleAnimation4);
				if (this.IsFadeEnabled)
				{
					DoubleAnimation doubleAnimation5 = new DoubleAnimation();
					doubleAnimation5.set_From(new double?(0.0));
					doubleAnimation5.set_To(new double?(0.3));
					doubleAnimation5.set_Duration(timeSpan);
					doubleAnimation5.set_EasingFunction(easingFunction);
					DoubleAnimation doubleAnimation6 = doubleAnimation5;
					Storyboard.SetTarget(doubleAnimation6, uIElement3);
					Storyboard.SetTargetProperty(doubleAnimation6, new PropertyPath(UIElement.OpacityProperty));
					this._backgroundResizeStoryboard.get_Children().Add(doubleAnimation6);
				}
			}
			TransformGroup transformGroup = new TransformGroup();
			if (this._rootVisual != null)
			{
				PageOrientation orientation = this._rootVisual.get_Orientation();
				if (orientation != 18)
				{
					if (orientation == 34)
					{
						PresentationFrameworkCollection<Transform> arg_532_0 = transformGroup.get_Children();
						RotateTransform rotateTransform = new RotateTransform();
						rotateTransform.set_Angle(-90.0);
						arg_532_0.Add(rotateTransform);
						PresentationFrameworkCollection<Transform> arg_559_0 = transformGroup.get_Children();
						TranslateTransform translateTransform = new TranslateTransform();
						translateTransform.set_Y(this._rootVisual.get_ActualHeight());
						arg_559_0.Add(translateTransform);
					}
				}
				else
				{
					PresentationFrameworkCollection<Transform> arg_580_0 = transformGroup.get_Children();
					RotateTransform rotateTransform2 = new RotateTransform();
					rotateTransform2.set_Angle(90.0);
					arg_580_0.Add(rotateTransform2);
					PresentationFrameworkCollection<Transform> arg_5A7_0 = transformGroup.get_Children();
					TranslateTransform translateTransform2 = new TranslateTransform();
					translateTransform2.set_X(this._rootVisual.get_ActualWidth());
					arg_5A7_0.Add(translateTransform2);
				}
			}
			this._overlay.set_RenderTransform(transformGroup);
			if (this._page != null && this._page.get_ApplicationBar() != null && this._page.get_ApplicationBar().get_Buttons() != null)
			{
				IEnumerator enumerator = this._page.get_ApplicationBar().get_Buttons().GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						object current = enumerator.get_Current();
						ApplicationBarIconButton applicationBarIconButton = current as ApplicationBarIconButton;
						if (applicationBarIconButton != null)
						{
							applicationBarIconButton.add_Click(new EventHandler(this.OnEventThatClosesContextMenu));
							this._applicationBarIconButtons.Add(applicationBarIconButton);
						}
					}
				}
				finally
				{
					IDisposable disposable = enumerator as IDisposable;
					if (disposable != null)
					{
						disposable.Dispose();
					}
				}
			}
			this._overlay.get_Children().Add(this);
			Popup popup = new Popup();
			popup.set_Child(this._overlay);
			this._popup = popup;
			this._popup.add_Opened(delegate(object sender, EventArgs e)
			{
				this.OnOpened(new RoutedEventArgs());
			});
			base.add_SizeChanged(new SizeChangedEventHandler(this.OnContextMenuOrRootVisualSizeChanged));
			if (this._rootVisual != null)
			{
				this._rootVisual.add_SizeChanged(new SizeChangedEventHandler(this.OnContextMenuOrRootVisualSizeChanged));
			}
			this.UpdateContextMenuPlacement();
			if (base.ReadLocalValue(FrameworkElement.DataContextProperty) == DependencyProperty.UnsetValue)
			{
				DependencyObject source = this.Owner ?? this._rootVisual;
				DependencyProperty arg_712_1 = FrameworkElement.DataContextProperty;
				Binding binding = new Binding("DataContext");
				binding.set_Source(source);
				base.SetBinding(arg_712_1, binding);
			}
			this._popup.set_IsOpen(true);
			base.Focus();
			this._settingIsOpen = true;
			this.IsOpen = true;
			this._settingIsOpen = false;
		}
		private void ClosePopup()
		{
			if (this._backgroundResizeStoryboard != null)
			{
				using (IEnumerator<Timeline> enumerator = this._backgroundResizeStoryboard.get_Children().GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						DoubleAnimation doubleAnimation = (DoubleAnimation)enumerator.get_Current();
						double value = doubleAnimation.get_From().get_Value();
						doubleAnimation.set_From(doubleAnimation.get_To());
						doubleAnimation.set_To(new double?(value));
					}
				}
				Popup popup = this._popup;
				Panel overlay = this._overlay;
				this._backgroundResizeStoryboard.add_Completed(delegate(object sender, EventArgs e)
				{
					if (popup != null)
					{
						popup.set_IsOpen(false);
						popup.set_Child(null);
					}
					if (overlay != null)
					{
						overlay.get_Children().Clear();
					}
				});
				this._backgroundResizeStoryboard.Begin();
				this._backgroundResizeStoryboard = null;
				this._popup = null;
				this._overlay = null;
			}
			else
			{
				if (this._popup != null)
				{
					this._popup.set_IsOpen(false);
					this._popup.set_Child(null);
					this._popup = null;
				}
				if (this._overlay != null)
				{
					this._overlay.get_Children().Clear();
					this._overlay = null;
				}
			}
			base.remove_SizeChanged(new SizeChangedEventHandler(this.OnContextMenuOrRootVisualSizeChanged));
			if (this._rootVisual != null)
			{
				this._rootVisual.remove_SizeChanged(new SizeChangedEventHandler(this.OnContextMenuOrRootVisualSizeChanged));
			}
			using (List<ApplicationBarIconButton>.Enumerator enumerator2 = this._applicationBarIconButtons.GetEnumerator())
			{
				while (enumerator2.MoveNext())
				{
					ApplicationBarIconButton current = enumerator2.get_Current();
					current.remove_Click(new EventHandler(this.OnEventThatClosesContextMenu));
				}
			}
			this._applicationBarIconButtons.Clear();
			this._settingIsOpen = true;
			this.IsOpen = false;
			this._settingIsOpen = false;
			this.OnClosed(new RoutedEventArgs());
		}
	}
}
